module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage2.Stage2HomeGui".new()
local wEasing = require "wEasing"

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view

-----------------------------------------------------------------------------
	
end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	---------------------------------------
	local prior_scene = storyboard.getPrevious()
    storyboard.purgeScene( prior_scene )
	storyboard.printMemUsage()
	----------------------------------------

	local mainGroup = self.view
	
	-----------------------------------------------------------------------------
		
	local backgroundGroup, stageButtonGroup, homeButtonGroup, generateItemsGroup
	local bg,line
	local paper
	local paperTable = {}
	local generatePaper, moveToilet
	local totalTime,timeDelay, timeDelta = 20100,100,0
	local timerText
	local onMoveButtonTap
	local prePosition
	
	local countDown = 0
	local DELTA = 1.5
	local delta = DELTA
	local timeEachTurn = 30 * delta
	local dT = 1000 * delta
	
	local score = 0
	local scoreText
	local scoreMinus = 0
	local _gameOver
	local i
	local _score = {}
	
--------------------------- create group -------------------------------
	
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
------------------------- handler function ------------------------------	
function init()
	-- scoreText.alpha = 1
	delta = DELTA
	timeEachTurn = 30 * delta
	toilet.x = 2*gui.toilet.x
	toilet.y = gui.toilet.y
	toilet.rotation = 0
	_score = {32,34,36,38,40}
	i = 0
	prePosition = 0
	pauseButton.isVisible = true
	paper = generatePaper(1)
	table.insert(paperTable,paper)
	totalTimer = timer.performWithDelay( timeDelay, manageTotalTime, 0 )
	Runtime:addEventListener("enterFrame", checkCollision)
	leftButton:addEventListener("touch", onMoveButtonTap)
	rightButton:addEventListener("touch", onMoveButtonTap)
end

onMoveButtonTap = function(event)
	local t = event.target
	local phase = event.phase
	if(phase == "began")then
		if(t.id == "left") then
		toilet.x = toilet.x - gui.toilet.x
		if(toilet.x <= 0) then
			transition.to(toilet,{time = 500,x = toilet.x,y = toilet.y + 100,rotation = -30 })
			Runtime:removeEventListener("enterFrame", checkCollision)
			for k,v in pairs(paperTable)do
				table.remove(paperTable,k)
				display.remove(v)
			end
			timerText.text = 0 ..""
			timer.cancel(totalTimer)
			leftButton:removeEventListener("touch",onMoveButtonTap)
			rightButton:removeEventListener("touch",onMoveButtonTap)
			gameOver()
		end
		return
	end
	
		if(t.id == "right") then 
		toilet.x = toilet.x + gui.toilet.x
		if(toilet.x >= gui.displayWidth) then
			transition.to(toilet,{time = 500,x = toilet.x,y = toilet.y + 100,rotation = 30 })
			Runtime:removeEventListener("enterFrame", checkCollision)
			for k,v in pairs(paperTable)do
				table.remove(paperTable,k)
				display.remove(v)
			end
			timerText.text = 0 ..""
			timer.cancel(totalTimer)
			leftButton:removeEventListener("touch",onMoveButtonTap)
			rightButton:removeEventListener("touch",onMoveButtonTap)
			gameOver()
		end
		return
	end
	end
end

function gameOver()
	-- _gameOver.alpha = 1
	local temp = 0
		if(score < 32)then
			temp = 0
		elseif(score >= 32 and score <34)then
			temp = 1
		elseif(score >= 34 and score < 36)then
			temp = 2
		elseif(score >= 36 and score < 38)then
			temp = 3
		elseif(score >= 38 and score <40)then
			temp = 4
		elseif(score >= 40)then
			temp = 5
		end
	local g1 = require "popup.popupWin".new(score,temp,_score,onReplayButtonTap)
	transition.to(g1,{time = 2000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic,onStart = function() g1.y = -500 end})
end

function generatePaper(coeffcient)
	local position = math.random(4)
	while(position == prePosition)do
		position = math.random(1,4)
	end
	prePosition = position
	local _paper = display.newImageRect(generateItemsGroup, gui.paper.fn, gui.paper.w, gui.paper.h)
		_paper.x = position*gui.paper.x
		_paper.y = 0
		_paper.position = position

	
	countDown = countDown + 1
	_paper.remainTime = dT*coeffcient
	_paper.startTime = system.getTimer()
	
	_paper.tran = transition.to(_paper,{time = dT*coeffcient, alpha = 1, x = _paper.x, y = 300})
	return _paper
end

function checkCordinate(objectA, objectB)
	if((objectA.x == objectB.x)
		and (objectB.y >=(objectA.y - objectA.contentHeight/2))
		-- and (objectB.y <=(objectA.y +(objectB.contentHeight/2 + objectB.contentHeight/2))))then
		)then
			score = score + 1
			countDown = countDown - 1
			return true
		end
	return false
end

function checkCollision()
	
	i = i + 1
	-- checkCordinate(toilet,paper)
	-- if(countDown == 0) then
		-- display.remove(paper)
		-- i = 0
		-- paper = generatePaper(1)
	-- end
	-- if(i >= timeEachTurn and paper.y >= toilet.y) then
		-- score = score - scoreMinus
		-- display.remove(paper)
		-- i = 0
		-- paper = generatePaper(1)
	-- end
	-- scoreText.text = score
	
	if(i >= timeEachTurn) then
		i = 0
		paper = generatePaper(1)
		table.insert(paperTable,paper)
		-- mainGroup:insert(paperTable)
	end
	for k,v in pairs(paperTable)do
		if(v.y >= toilet.y)then
			table.remove(paperTable,k)
			display.remove(v)
		elseif(checkCordinate(toilet,v))then
			table.remove(paperTable,k)
			display.remove(v)
		end	
	end
	scoreText.text = score
end

function onStartPopup()
	timer.pause(totalTimer)
	Runtime:removeEventListener("enterFrame",checkCollision)
	for k,v in pairs(paperTable)do
		v.remainTime = dT - (system.getTimer() - v.startTime)
		transition.cancel(v.tran)
	end
end

function onResumeFromPopup()
	timer.resume(totalTimer)
	for k,v in pairs(paperTable)do
		v.tran = transition.to(v,{time = v.remainTime, alpha = 1, x = v.x, y = 300})
	end
	Runtime:addEventListener("enterFrame",checkCollision)
end

function onReplayButtonTap()
	Runtime:removeEventListener("enterFrame",checkCollision)
	timer.cancel(totalTimer)
	leftButton:removeEventListener("touch", onMoveButtonTap)
	rightButton:removeEventListener("touch", onMoveButtonTap)
	-- print (generateItemsGroup.numChildren ,"1111111111111111111111")
	-- for k,v in pairs(paperTable)do
		-- table.remove(paperTable,k)
		-- display.remove(v)
	-- end
	paperTable = {}
	for i = generateItemsGroup.numChildren, 1, -1 do
		generateItemsGroup:remove(generateItemsGroup[i])
	end
	_gameOver.alpha = 0
	score = 0
	totalTime = 20100
	init()
end

-------------------- background and button ---------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y
	
line = display.newImageRect(backgroundGroup,gui.line.fn,gui.line.w,gui.line.h)
	line.x = gui.line.x
	line.y = gui.line.y

leftButton = display.newImageRect(stageButtonGroup, gui.leftButton.fn, gui.leftButton.w, gui.leftButton.h)
	leftButton.x = gui.leftButton.x
	leftButton.y = gui.leftButton.y
	leftButton.id = "left"
	
rightButton = display.newImageRect(stageButtonGroup, gui.rightButton.fn, gui.rightButton.w, gui.rightButton.h)
	rightButton.x = gui.rightButton.x
	rightButton.y = gui.rightButton.y
	rightButton.id = "right"

	
-- toilet = display.newImageRect(stageButtonGroup, gui.toilet.fn, gui.toilet.w, gui.toilet.h)
	-- toilet.x = gui.toilet.x
	-- toilet.y = gui.toilet.y
	-- toilet.alpha = 0
	
local sheet1 = graphics.newImageSheet( gui.tl.fn, { width=218, height=224, numFrames=2 } )
toilet = display.newSprite( sheet1, { name = "tl", start=1, count=2, time=250 } )
	toilet.x = gui.toilet.x
	toilet.y = gui.toilet.y
	toilet.xScale = 0.5
	toilet.yScale = 0.5
	toilet:play()
stageButtonGroup:insert(toilet)
		
mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(homeButtonGroup)


-------------------------------------------------------------------------------------
----------------------------- Score
-------------------------------------------------------------------------------------

scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	-- scoreText.alpha = 0
homeButtonGroup:insert(scoreText)

_gameOver = display.newText(homeButtonGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	_gameOver.x = display.contentCenterX
	_gameOver.y = display.contentCenterY
	_gameOver:setTextColor(unpack(gui.score.color))
	_gameOver.alpha = 0
		
-------------------- helper function -------------------


function manageTotalTime()
	totalTime = totalTime - 100
	if(totalTime <= 17000 and totalTime > 14000)then
		delta = 0.6*DELTA
		-- delta = DELTA
		timeEachTurn = 30 * delta
		-- dT = 1000 * delta
	elseif(totalTime <= 14000 and totalTime > 10000)then
		delta = 0.4*DELTA
		-- delta = DELTA
		timeEachTurn = 30 * delta
		-- dT = 1000 * delta
	elseif(totalTime <= 10000 and totalTime >0)then
		delta = 0.3*DELTA
		-- delta = DELTA
		timeEachTurn = 30 * delta
		-- dT = 1000 * delta
	
    elseif(totalTime <= 0) then
		pauseButton.isVisible = false
		timerText.text = 0 ..""
		timer.cancel(totalTimer)
		Runtime:removeEventListener("enterFrame", checkCollision)
		leftButton:removeEventListener("touch",onMoveButtonTap)
		rightButton:removeEventListener("touch",onMoveButtonTap)
		for k,v in pairs(paperTable)do
			table.remove(paperTable,k)
			display.remove(v)
		end
		
		local temp = 0
		if(score < 32)then
			temp = 0
		elseif(score >= 32 and score <34)then
			temp = 1
		elseif(score >= 34 and score < 36)then
			temp = 2
		elseif(score >= 36 and score < 38)then
			temp = 3
		elseif(score >= 38 and score <40)then
			temp = 4
		elseif(score >= 40)then
			temp = 5
		end
		
		local g1 = require "popup.popupWin".new(score,temp,_score,onReplayButtonTap)
		
		transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
	end
	timerText.text = math.round(totalTime/100)/10
end


-----------------------------------------------------------------------------
pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		mainGroup:insert(group2)
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup})
	end
})
replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w*1.2,
	overY = gui.replayButton.h*1.2,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})

mainGroup:insert(pauseButton)
mainGroup:insert(replayButton)
---------------------------- [[Timer]]-------------------

timerText = display.newText(gui.timer.text, gui.timer.left, gui.timer.top, gui.timer.font, gui.timer.fontSize)
	timerText:setTextColor(gui.timer.red, gui.timer.green, gui.timer.red, gui.timer.alpha) 
	timerText.x = gui.timer.x
	timerText.y = gui.timer.y
	-- timerText.alpha = 0
mainGroup:insert(timerText)

--------------------- run ---------------------------------
init()
	
	
	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene